package com.base.component.ai.workflow.handle;

import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Component;

import com.base.component.ai.agent.bo.ContextBO;
import com.base.component.ai.agent.bo.ContextParamBO;
import com.base.component.ai.platform.core.utils.Utils;
import com.base.component.ai.workflow.core.NodeHandle;
import com.base.component.ai.workflow.flow.Flow;
import com.base.component.ai.workflow.logs.NodeLog;
import com.base.component.ai.workflow.node.Node;
import com.base.component.ai.workflow.node.NodeDify;
import com.gitee.magic.context.ConverterEditorUtils;
import com.gitee.magic.core.annotations.Column;
import com.gitee.magic.core.json.JsonObject;
import com.gitee.magic.framework.base.rest.HttpRequest;
import com.gitee.magic.framework.base.rest.HttpWrapper;

import lombok.Data;

@Component
public class NodeHandleDify<MSG,AP extends ContextParamBO,PP> implements NodeHandle<MSG,AP,PP>{

	private static final String DATA="data: (\\{.*\\})";
	
	@Override
	public <T extends Node> boolean support(Class<T> cls) {
		return cls.equals(NodeDify.class);
	}

	@Override
	public <T extends Node>List<Flow> execute(ContextBO<MSG,AP,PP> context,Map<String,Object> params,Flow flow,T node,Consumer<NodeLog> c) {
		NodeDify d=(NodeDify)node;

		String accessKey="app-6IznT5rA26gNn2SNsJl6QOvi";
		String url="http://dify.sparktalk.ai:8080/v1/workflows/run";
		
		DifyWorkflowRequestBO dwr=new DifyWorkflowRequestBO();
		JsonObject inputJson=new JsonObject();
		for(String name:d.getInputs()) {
			if(params.containsKey(name)) {
				inputJson.put(name, String.valueOf(params.get(name)));
			}
		}
		dwr.setInputs(inputJson);
		dwr.setResponseMode("streaming");
		dwr.setUser(d.getUser());
		HttpRequest request=new HttpRequest(url);
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setHeader(HttpWrapper.AUTHORIZATION,accessKey);
		request.setHeader("accept","*/*");
		System.out.println(ConverterEditorUtils.converterObject(dwr).toString());
		request.setBodyContent(ConverterEditorUtils.converterObject(dwr).toString());
		HttpWrapper wrapper=new HttpWrapper();
		HttpURLConnection connection=wrapper.requestConnect(request);
		Utils.streamConsumer200And201(connection, (s)->{
			Matcher matcher = Pattern.compile(DATA).matcher(s);
            while (matcher.find()) {
                String data = matcher.group(1);
                System.out.println(data);
            }
		});
		return flow.getNexts();
	}
	
	@Data
	public static class DifyWorkflowRequestBO {
		
		private JsonObject inputs;
		
		@Column("response_mode")
		private String responseMode;
		
		private String user;
		
	}
	
	@Data
	public static class DifyWorkflowBO<T> {
		
		/**
		 * workflow_started(流程开始)
		 * node_started(节点开始)
		 * node_finished(节点结束)
		 * workflow_finished(流程结束)
		 */
		private String event;

		@Column("workflow_run_id")
		private String workflowRunId;
		
		@Column("task_id")
		private String taskId;
		
		private T data;
		
	}
	
	@Data
	public static class DifyWorkflowEventDataBO {
		
		@Column("node_type")
		private String nodeType;
		
		private JsonObject inputs;
		
		private JsonObject outputs;
		
	}
	
	public static void main(String[] args) {
		String accessKey="Bearer app-6IznT5rA26gNn2SNsJl6QOvi";
		String url="http://dify.sparktalk.ai:8080/v1/workflows/run";
		
		DifyWorkflowRequestBO dwr=new DifyWorkflowRequestBO();
		JsonObject inputJson=new JsonObject();
		inputJson.put("question", "说说你的故事");
		inputJson.put("age", "25");
		dwr.setInputs(inputJson);
		dwr.setResponseMode("streaming");
		dwr.setUser("abc-123");
		
		HttpRequest request=new HttpRequest(url);
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setHeader(HttpWrapper.AUTHORIZATION,accessKey);
		request.setHeader("accept","*/*");
		System.out.println(ConverterEditorUtils.converterObject(dwr).toString());
		request.setBodyContent(ConverterEditorUtils.converterObject(dwr).toString());
		HttpWrapper wrapper=new HttpWrapper();
		HttpURLConnection connection=wrapper.requestConnect(request);
		Utils.streamConsumer200And201(connection, (s)->{
			Matcher matcher = Pattern.compile(DATA).matcher(s);
            while (matcher.find()) {
                String data = matcher.group(1);
                System.out.println(data);
                JsonObject json=new JsonObject(data);
                String evnetName=json.getString("event");
                if("node_finished".equals(evnetName)){
                	if(json.has("node_type")) {
                		String nodeType=json.getString("node_type");
                    	if("llm".equals(nodeType)) {
                    		
                    	}else if("end".equals(nodeType)) {
                    		
                    	}
                	}
                }
            }
		});
	}
	
	
}
